home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_13_10 / mashlan / heapptr.h < prev   
C/C++ Source or Header  |  1995-04-14  |  2KB  |  83 lines

  1. // heapptr.h listing 2
  2. // copyright 1995 Robert Mashlan
  3.  
  4. #ifndef __HEAPPTR_H
  5. #define __HEAPPTR_H
  6.  
  7. #include <stddef.h>
  8.  
  9. template<class T>
  10. class HeapPtr {
  11.     public:
  12.       // constructor for arrays
  13.       HeapPtr( size_t nelems )
  14.          : pref(Ref::newRef(new T[nelems],1))
  15.          {}
  16.       // constructor for non-arrays
  17.       HeapPtr( T* p = 0 )
  18.          : pref(Ref::newRef(p))
  19.          {}
  20.       // copy constructor
  21.       HeapPtr( const HeapPtr<T>& orig )
  22.          : pref(orig.pref->copyRef())
  23.          {}
  24.       ~HeapPtr()
  25.          { pref->delRef(); }
  26.  
  27.       T* getp() const
  28.          { return pref->getp(); }
  29.       // operators
  30.       operator T*() const
  31.          { return getp(); }
  32.       HeapPtr<T>& operator=( const HeapPtr<T>& orig )
  33.          {
  34.             pref->delRef();
  35.             pref=orig.pref->copyRef();
  36.             return *this;
  37.          }
  38.       HeapPtr<T>& operator=( size_t nelems )
  39.          {
  40.            pref->delRef();
  41.            pref = Ref::newRef(new T[nelems],1);
  42.            return *this;
  43.          }
  44.       HeapPtr<T>& operator=( T* p )
  45.          {
  46.            pref->delRef();
  47.            pref = Ref::newRef(p);
  48.            return *this;
  49.          }
  50.       HeapPtr<T>& operator()( size_t nelems )
  51.          { return operator=(nelems); }
  52.       HeapPtr<T>& operator()( T *p )
  53.          { return operator=(p); }
  54.       HeapPtr<T>& operator()( const HeapPtr<T>& hp )
  55.          { return operator=(hp); }
  56.       HeapPtr<T>& empty()
  57.          { return operator=((T*)0); }
  58.    protected:
  59.       class Ref {
  60.          public:
  61.             static Ref *newRef( T *p, bool isarray=false )
  62.                { return new Ref(p,isarray); }
  63.             void delRef()
  64.                { ref--; if(ref==0) delete this;  }
  65.             Ref *copyRef()
  66.                { ref++; return this; }
  67.             T* getp() const
  68.                { return p; }
  69.          protected:
  70.             Ref( T* p, bool isarray )
  71.                : ref(1), p(p), isarray(isarray)
  72.                {}
  73.             ~Ref()
  74.                { isarray ? delete []p : delete p; }
  75.             T *p;
  76.             long ref;
  77.             bool isarray;
  78.       };
  79.       Ref *pref;
  80. };
  81.  
  82. #endif
  83.